package com.wzw.springcloudgateway.predicates;

import lombok.Data;
import lombok.experimental.Accessors;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.cloud.gateway.handler.predicate.GatewayPredicate;
import org.springframework.http.HttpHeaders;
import org.springframework.web.server.ServerWebExchange;

import java.util.List;
import java.util.Objects;
import java.util.function.Predicate;

/**
 * 扩展实现自定义谓词函数
 *
 * @author Wangzhiwen
 */
public class TerminalRoutePredicateFactory extends AbstractRoutePredicateFactory<TerminalRoutePredicateFactory.Config> {

    public static final String TERMINAL = "terminal";

    public TerminalRoutePredicateFactory() {
        super(Config.class);
    }

    @Override
    public List<String> shortcutFieldOrder() {
        return List.of(TERMINAL);
    }

    @Override
    public ShortcutType shortcutType() {
        return ShortcutType.GATHER_LIST_TAIL_FLAG;
    }

    @Override
    public Predicate<ServerWebExchange> apply(Config config) {
        return (GatewayPredicate) exchange -> {
            HttpHeaders headers = exchange.getRequest().getHeaders();
            // 不好含指定请求头
            if (!headers.containsKey(TERMINAL)) {
                return false;
            }
            // 指定请求头为空
            List<String> var = headers.get(TERMINAL);
            if (Objects.requireNonNull(var).isEmpty()) {
                return false;
            }
            // 请求头内容相同时才放行
            return config.getTerminal().equals(var.get(0));
        };
    }

    /**
     * 配置信息载体，用于比较请求里转载的值与配置文件里指定的值是否相同
     */
    @Data
    @Accessors(chain = true)
    public static class Config {
        private String terminal;
    }

}
